package user.losacorp.blogger;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;

import user.losacorp.xml.FeedFactory;

import com.google.gdata.client.GoogleService;
import com.google.gdata.data.Entry;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

public class MyBloggerClient {

	private List<Entry> entryList;
	// private GoogleService myService = null;
	private URL postUrl = null;

	public MyBloggerClient(GoogleService myService, String blogID,
			String username, String password) {
		entryList = new ArrayList<Entry>();
		try {
			myService.setUserCredentials(username, password);
			postUrl = new URL("http://www.blogger.com/feeds/" + blogID
					+ "/posts/default");
		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			// System.out.println("Error de autenticacion Blogger: "
			// + e.getMessage());
			FeedFactory.logger.log(Level.SEVERE,
					"Error de autenticacion Blogger: ", e.getMessage());
		} catch (MalformedURLException e) {
//			System.out.println("URL malformada: " + e.getMessage());
			FeedFactory.logger.log(Level.SEVERE, "URL malformada: ", e.getMessage());
		}

	}

	public void addEntryBlog(String title, String contentHtmlText,
			boolean isDraft) {
		Entry myEntry = new Entry();
		myEntry.setTitle(new PlainTextConstruct(title));
		myEntry.setContent(new PlainTextConstruct(contentHtmlText));
		myEntry.setDraft(isDraft);
		entryList.add(myEntry);

	}

	public void uploadEntry(GoogleService myService, Entry entry) {
		try {
			myService.insert(postUrl, entry);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void updataBlog(GoogleService myService) throws ServiceException {
		for (Entry entry : entryList) {
			try {
				myService.insert(postUrl, entry);
			} catch (IOException e) {
				throw new ServiceException(
						"Error al agregar entrada al blog. Tiro excepcion: "
								+ e.getMessage());
			}

		}

	}

	public static void main(String[] args) {
		GoogleService myService = new GoogleService("blogger",
				"exampleCo-exampleApp-1");
		MyBloggerClient mbc = new MyBloggerClient(myService, "",
				"javierlosada@gmail.com", "carfax90");
		mbc.addEntryBlog("Nueva entrada", "<p>Entrada Texto</p>", true);
		try {
			mbc.updataBlog(myService);
		} catch (ServiceException e) {
//			System.out.println("Error:\n" + e.getMessage());
			FeedFactory.logger.log(Level.SEVERE, "Error:\n", e.getMessage());
		}
	}

}
